package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pic-text-mgr/cache"
	"pic-text-mgr/modles"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	context := c.PostForm("context")
	book := modles.Book{
		Title:   title,
		Context: context,
	}
	tx := modles.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "发布失败",
			})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	err := modles.DB.Create(&book).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	err = tx.Commit().Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "Add_" + title
	modles.DB.Find(&book)
	marshal, _ := json.Marshal(book)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Second*10)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var book []modles.Book
	err := modles.DB.Offset(offset).Limit(size).Find(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": book,
	})
	return
}

func Find(c *gin.Context) {
	id := c.Query("id")
	var book modles.Book
	err := modles.DB.Where("id=?", id).Find(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	redisKey := "find_" + id
	modles.DB.Where("id=?", id).Find(&book)
	marshal, _ := json.Marshal(book)
	cache.Rdb.Set(cache.Ctx, redisKey, marshal, time.Hour*1)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": book,
	})
	return
}
